/**
 * Definition for singly-linked com.vernhe.list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution_147 {
    public class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

    public ListNode insertionSortList(ListNode head) {
        /*
        //空链表
        if(head == null) {
            return null;
        }
        //只由一个元素
        if (head.next == null) {
            return head;
        }

        //定义左右链表，左边链表从链表第一个元素开始，右边链表从第二个元素开始

        //初始化左边的链表
        ListNode leftListNode = new ListNode(head.val);

        //初始化右边的链表
        ListNode rightListNode = head.next;

        //当右边的链表还有数据时就继续遍历
        //遍历的指针
        ListNode l1 = leftListNode;
        ListNode l2 = l1;
        ListNode r = rightListNode;

        while (r != null) {
            //获得第一个的值
            int current = r.val;

            //遍历左边的数据进行逐个比较
            while (l1 != null) {
                l2 = l1.next;

                //l2不为空
                if (l2 != null) {
                    if (l1.val < current && l2.val > current) {

                    }
                }else { //l2为空

                }

            }

            //往后遍历
            r = r.next;
        }
        */

        //只有一个或者为空
        if (head == null || head.next == null) {
            return head;
        }

        ListNode dummy = new ListNode(0);
        ListNode pre = head;
        ListNode cur = head.next;
        dummy.next = head;
        while (cur != null) {
            if (pre.val <= cur.val) {
                //有序就往后走
                pre = cur;
                cur = cur.next;
            } else {
                //当前值比前一个大的时候，找到合适的位置插入 p < cur <p.next
                ListNode p = dummy;
                while (p.next != cur && p.next.val < cur.val) {
                    p = p.next;
                }

                //把 cur 插入到p和p.next中间
                pre.next = cur.next;
                cur.next = p.next;
                p.next = cur;

                cur = pre.next;
            }
        }
        return dummy.next;
    }
}

